/* eslint-disable camelcase */
import { observable, autorun, action, runInAction, computed } from 'mobx';
import AV from 'leancloud-storage';

// https://leancloud.cn/docs/leanstorage_guide-js.html#hash765832
class TodoStore {
  dailyTodos = [
    { name: '做事专注到极致', isComplete: false, timeFlag: 0, isPrincipal: true },
    { name: '自信、敢于担当', isComplete: false, timeFlag: 0, isPrincipal: true },
    { name: '腰背挺直、不要抖腿', isComplete: false, timeFlag: 0, isPrincipal: true },
    { name: '控制情绪、控制欲望', isComplete: false, timeFlag: 0, isPrincipal: true },
    { name: '学会倾听，表述观点时有理有据', isComplete: false, timeFlag: 0, isPrincipal: true },
    { name: '与人交往，不要刻意拘谨，大大方方交谈', isComplete: false, timeFlag: 0, isPrincipal: true },
    { name: '学习理财，定期储蓄和减少不必要的开支', isComplete: false, timeFlag: 0, isPrincipal: true },

    { name: '刮胡须', isComplete: false, timeFlag: 1, isPrincipal: true },
    { name: '洗衣服', isComplete: false, timeFlag: 1, isPrincipal: true },
    { name: '做早餐(清淡不油腻)', isComplete: false, timeFlag: 1, isPrincipal: true },
    { name: '洗漱、洗面奶、保湿', isComplete: false, timeFlag: 1, isPrincipal: true },
    { name: '着装清爽整洁', isComplete: false, timeFlag: 1, isPrincipal: true },

    { name: '运动', isComplete: false, timeFlag: 2, isPrincipal: true },
    { name: '洗漱、刷牙', isComplete: false, timeFlag: 2, isPrincipal: true },
    { name: '洗面奶、保湿', isComplete: false, timeFlag: 2, isPrincipal: true },
    { name: '30分钟阅读', isComplete: false, timeFlag: 2, isPrincipal: true },
    { name: '11点半前睡觉', isComplete: false, timeFlag: 2, isPrincipal: true },
  ]
  acl = null //角色权限
  @observable user = null //登录的用户
  @observable todos = [] //当日的任务列表

  /**
   * 用户登录
   */
  @action userLogin() {
    AV.User.currentAsync().then(res => {
      if (res == null) {
        AV.User.logIn('admin', 'admin').then(res => {
          this.user = res
          this.reduceNewAcl()
          this.getTodayTodoList()
        }).catch(console.log)
      } else {
        this.user = res
        this.reduceNewAcl()
        this.getTodayTodoList()
      }
    }).catch(console.log)
  }

  /**
   * 生成用户权限，仅自己可读可写
   */
  reduceNewAcl() {
    var newAcl = new AV.ACL();
    newAcl.setPublicReadAccess(false);
    newAcl.setReadAccess(this.user, true)
    newAcl.setWriteAccess(this.user, true);
    this.acl = newAcl
  }

  /**
   * 用户退出
   */
  @action userLogout() {
    AV.User.logOut().then(res => {
      this.user = null
    }).catch(console.log)
  }

  /**
  * 生成今日的默认任务列表
  */
  @action createTodayTodoList() {
    var Todo = AV.Object.extend('Todos');

    let objects = this.dailyTodos.map(item => {
      let todo = new Todo();

      todo.set('name', item.name); //任务名称
      todo.set('isComplete', item.isComplete); //是否已完成
      todo.set('timeFlag', item.timeFlag);// 0整天 1早上 2晚上
      todo.set('isPrincipal', item.isPrincipal); //是否是主要任务

      // 将 ACL 实例赋予 Post 对象
      todo.setACL(this.acl);
      return todo
    })

    AV.Object.saveAll(objects).then((res) => {
      this.todos = res
    }).catch(console.log)
  }

  /**
   * 查找当天的任务列表
   * 如果当天无任务则新建每日任务
   */
  @action getTodayTodoList() {
    let currentDate = new Date()
    currentDate.setUTCHours(0, 0, 0, 0)

    var query = new AV.Query('Todos');
    query.greaterThanOrEqualTo('createdAt', currentDate);
    query.find().then(res => {
      runInAction(() => {
        if (res.length == 0) {
          this.createTodayTodoList()
        } else {
          this.todos = res
        }
      })
    }).catch(err => {
      console.log(err)
      console.log(AV.ErrorCode)
    })
  }

  /**
   * 任务列表，按照 timeFlag 排好序
   */
  @computed get todoList() {
    if (this.todos == null || this.todos == undefined || this.todos.length == 0) {
      return []
    }

    const localData = this.todos.map(item => {
      return {
        objectId: item.get('objectId'),
        name: item.get('name'),
        isComplete: item.get('isComplete'),
        timeFlag: item.get('timeFlag'),
        isPrincipal: item.get('isPrincipal'),
        createdAt: item.get('createdAt'),
        updatedAt: item.get('updatedAt'),
      }
    })

    let dayTasks = localData.filter(item => item.timeFlag == 0).sort(this.taskSort)
    let morningTasks = localData.filter(item => item.timeFlag == 1).sort(this.taskSort)
    let eveningTasks = localData.filter(item => item.timeFlag == 2).sort(this.taskSort)

    return [
      { title: '白天', data: dayTasks, },
      { title: '早上', data: morningTasks, },
      { title: '晚上', data: eveningTasks, },
    ]
  }

  @action updateTodo(objectId) {
    const todo = this.todos.filter(item => item.get('objectId') == objectId)[0]
    todo.set('isComplete', !todo.get('isComplete'))
    todo.save().then(res => {//更新完成
      this.todos = this.todos.map(item => {
        if (item.get('objectId') == res.get('objectId')) {
          return res
        } else {
          return item
        }
      })
    })
  }

  taskSort(first, second) {
    if (first.isComplete == second.isComplete) {
      return first.name.length - second.name.length
    } else if (first.isComplete) {
      return 1
    } else {
      return -1
    }
  }

}

let store = new TodoStore()

// /* 观察状态改变的函数 */
// autorun(function () {
//   console.log(
//     `todoList = ${store.todoList}`,
//   );
// }, { delay: 500 });

export default store